//
//  RemoteSegmentViewController.swift
//  ZhiTing
//
//  Created by macbook on 2022/5/12.
//

import UIKit
import JXSegmentedView

#if !(targetEnvironment(simulator))
class RemoteSegmentViewController: BaseViewController {
    var myUID = ""
    var mypwd = ""
    var device = Device()
    private var segmentedDataSource: JXSegmentedTitleDataSource?
    private var segmentedView: JXSegmentedView?
    private var listContainerView: JXSegmentedListContainerView?
    
    //file://\(ZTZipTool.getDocumentPath())/\(device.plugin_id)/html/index.html#/camera-replay?iid=\(myUID)/plugin_id=\(device.plugin_id)
    private lazy var cloudVC = CloudRemotePlaybackViewController(link: "file://\(ZTZipTool.getDocumentPath())/\(device.plugin_id)/html/index.html#/camera-replay?iid=\(myUID)&plugin_id=\(device.plugin_id)").then {
        $0.mypwd = self.mypwd
        $0.myUID = self.myUID
        $0.isEmbeddedPage = true
    }
    
    private lazy var TFVC = RemotePlaybackViewController().then {
        $0.mypwd = self.mypwd
        $0.myUID = self.myUID
        $0.clickFullScreenCallback = {[weak self] in
            guard let self = self else {return}
            self.intoFullScreen()
        }
    }

    private lazy var backBtn: Button = {
        let btn = Button()
        btn.frame.size = CGSize.init(width: 30, height: 30)
        btn.setImage(.assets(.navigation_back), for: .normal)
        btn.addTarget(self, action: #selector(navPop), for: .touchUpInside)
        btn.contentHorizontalAlignment = .left
        btn.isEnhanceClick = true
        return btn
    }()
    
    private lazy var line = UIView().then {
        $0.backgroundColor = .custom(.gray_eeeeee)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
            appDelegate.isAllOrientation = true
        }
        navigationController?.setNavigationBarHidden(true, animated: false)
    }

    
    private func intoFullScreen(){
        DispatchQueue.main.async {
            if UIDevice.current.orientation == .portrait {
                let oriention = UIInterfaceOrientation.landscapeRight // 设置屏幕为横屏
                UIDevice.current.setValue(oriention.rawValue, forKey: "orientation")
                UIViewController.attemptRotationToDeviceOrientation()
            }else{
                //强制归正：
                let oriention = UIInterfaceOrientation.portrait // 设置屏幕为竖屏
                UIDevice.current.setValue(oriention.rawValue, forKey: "orientation")
                UIViewController.attemptRotationToDeviceOrientation()
            }
        }
    }

    
    //屏幕发生旋转
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        if size.width > size.height {//横屏
            ZTLog("当前为横屏")
            //隐藏header，通知页面进入横屏
            if let segmentedView = segmentedView, let listContainerView = listContainerView {
                switch segmentedView.selectedIndex {
                case 1 ://TF卡
                    listContainerView.snp.remakeConstraints {
                        $0.top.equalToSuperview()
                        $0.left.right.bottom.equalToSuperview()
                    }
                    view.bringSubviewToFront(listContainerView)
                    //通知页面发生变化
                    TFVC.setupLandscapeUI(size: size)
                default:
                    break
                }
                
            }
        }else{//竖屏
            ZTLog("当前为竖屏")
            if let segmentedView = segmentedView, let listContainerView = listContainerView {
                switch segmentedView.selectedIndex {
                case 1 ://TF卡
                    listContainerView.snp.remakeConstraints {
                        $0.top.equalTo(segmentedView.snp.bottom).offset(5)
                        $0.left.right.bottom.equalToSuperview()
                    }
                    view.bringSubviewToFront(listContainerView)
                    //通知页面发生变化
                    TFVC.setupPortraitUI(size: size)
                default:
                    break
                }
            }
        }
    }
    
    
    override func setupViews() {
        /// segments
        let titles = ["云盘存储".localizedString, "TF存储卡".localizedString]
        //配置数据源
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.isTitleColorGradientEnabled = true
        dataSource.titles = titles
        dataSource.titleNormalColor = .custom(.gray_94a5be)
        dataSource.titleSelectedColor = .custom(.blue_3699ff)
        dataSource.titleNormalFont = .font(size: 14, type: .bold)
        dataSource.isItemSpacingAverageEnabled = true
        
        segmentedDataSource = dataSource
        //配置指示器
        let indicator = JXSegmentedIndicatorLineView()
        indicator.verticalOffset = 5
        indicator.indicatorWidthIncrement = -10
        indicator.indicatorColor = .custom(.white_ffffff)
        
        
        indicator.indicatorWidth = JXSegmentedViewAutomaticDimension
        segmentedView = JXSegmentedView()
        segmentedView?.indicators = [indicator]
        
        segmentedView?.dataSource = segmentedDataSource
        segmentedView?.delegate = self
        
        
        listContainerView = JXSegmentedListContainerView(dataSource: self)
        listContainerView?.scrollView.isScrollEnabled = false
        segmentedView?.listContainer = listContainerView
        
        
        if let segmentedView = segmentedView, let listContainerView = listContainerView {
            view.addSubview(listContainerView)
            view.addSubview(segmentedView)
            view.addSubview(line)
            view.addSubview(backBtn)

            segmentedView.snp.makeConstraints {
                $0.top.equalToSuperview().offset(Screen.statusBarHeight)
                $0.width.equalTo(Screen.screenWidth * 2 / 3)
                $0.height.equalTo(Screen.k_nav_height - Screen.statusBarHeight)
                $0.centerX.equalToSuperview()
            }
            
            line.snp.makeConstraints {
                $0.left.right.equalToSuperview()
                $0.height.equalTo(0.5)
                $0.top.equalToSuperview().offset(Screen.k_nav_height + 5)
            }

            backBtn.snp.makeConstraints {
                $0.centerY.equalTo(segmentedView.snp.centerY)
                $0.width.equalTo(8)
                $0.height.equalTo(14)
                $0.left.equalToSuperview().offset(15)
            }
            
            listContainerView.snp.makeConstraints {
                $0.top.equalTo(segmentedView.snp.bottom).offset(5)
                $0.left.right.bottom.equalToSuperview()
            }
        }
    }
}

extension RemoteSegmentViewController: JXSegmentedViewDelegate, JXSegmentedListContainerViewDataSource {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        if let titleDataSource = segmentedView?.dataSource as? JXSegmentedBaseDataSource {
            return titleDataSource.dataSource.count
        }
        return 0
    }
    
    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        if index == 0 {
            return cloudVC
        } else {
            return TFVC
        }
        
    }
    
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        if let dotDataSource = segmentedDataSource as? JXSegmentedDotDataSource {
            //update the datasource first
            dotDataSource.dotStates[index] = false
            //then reloadItem(at: index)
            segmentedView.reloadItem(at: index)
        }
    }
}
#endif
